﻿using Application.Share.Event;
using Application.Share.Model;
using Application.Share.PrismNames;
using Prism.Commands;
using Prism.Events;
using Prism.Modularity;
using Prism.Regions;
using ReactiveUI;
using System.Windows.Input;

namespace Shell.ViewModels
{
    public class MainViewModel : ReactiveObject
    {
        private IEventAggregator EventAggregator { get; }
        private IRegionManager RegionManager { get; }
        private IModuleManager ModuleManager { get; }
        public ICommand LoadedCommand { get; }
        /// <summary>
        /// 所有硬件是否初始化完成
        /// </summary>
        public bool IsHardwareInitialized { get; set; } = false;

        public MainViewModel(
            IRegionManager regionManager, 
            IModuleManager moduleManager, 
            IEventAggregator eventAggregator)
        {
            ModuleManager = moduleManager;
            RegionManager = regionManager;
            EventAggregator = eventAggregator;
            LoadedCommand = new DelegateCommand(LoadWindow);
        }

        private void LoadWindow()
        {

            // ModuleManager.LoadModule("ApplicationLoginModule"); 如果启动了延时加载，这里需要手动加载
            RegionManager.RequestNavigate(RegionNames.MainRegion, "LoginView");
            EventAggregator.GetEvent<LoginSuccessEvent>().Subscribe(LoginSuccess,ThreadOption.UIThread);//订阅登录成功事件
            EventAggregator.GetEvent<InitializedSuccessEvent>().Subscribe(() => { IsHardwareInitialized = true; });//订阅硬件初始化成功事件
        }

        private void LoginSuccess(CurrentUser user)
        {
            if(IsHardwareInitialized)
            {
                //硬件已经初始化，直接进入主界面
                ModuleManager.LoadModule(ModuleNames.ApplicationMainModule);
                RegionManager.RequestNavigate(RegionNames.MainRegion, ViewNames.MainView);
            }
            else
            {
                ModuleManager.LoadModule(ModuleNames.ApplicationInitializeModule);
                RegionManager.RequestNavigate(RegionNames.MainRegion, ViewNames.InitializeView);
            }
           
        }
    }
}
